package stu.elasticsearch.jdbc;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;

class EsHttpClient {

    private final EsConfig esConfig;

    EsHttpClient(EsConfig esConfig) throws SQLException {
        this.esConfig = esConfig;
    }

    public String query(String sql) throws SQLException {
        try {
            String body = "{\"query\": \"" + sql + "\"}";
            return send(esConfig.getUrl(), "POST", esConfig.getAuth(), body);
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }

    boolean ping(long timeoutInMs) throws SQLException {
        try {
            send(esConfig.getUrl(), "HEAD", null, null);
            return true;
        } catch (Exception e) {
            throw new SQLException("Cannot ping server", e);
        }
    }

    /**
     * @param uri
     * @param method
     * @param auth
     * @param body   请求参数，Json串
     * @return
     */
    private String send(String uri, String method, String auth, String body) throws IOException {
        String result = null;
        OutputStream out = null;
        InputStream in = null;
        try {
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setReadTimeout(esConfig.getReadTimeout());
            connection.setConnectTimeout(esConfig.getConnectTimeout());
            connection.setAllowUserInteraction(false);
            connection.setRequestMethod(EsTool.isEmpty(method) ? "POST" : method);
            connection.setRequestProperty("content-type", "application/json;charset=utf-8");
            if (!EsTool.isEmpty(auth)) {
                connection.setRequestProperty("Authorization", auth);
            }
            connection.connect();// 获取连接

            if (!EsTool.isEmpty(body)) {
                out = connection.getOutputStream();
                out.write(EsTool.bytes(body, StandardCharsets.UTF_8));
                // out.flush();
            }

            in = connection.getInputStream();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();

            connection.disconnect();
        } catch (Exception e) {
            System.out.println("[请求异常][地址：" + uri + "][参数：" + body + "][错误信息：" + e.getMessage() + "]");
            throw e;
        } finally {
            try {
                if (null != in)
                    in.close();
                if (null != out)
                    out.close();
            } catch (Exception e2) {
                System.out.println("[关闭流异常][错误信息：" + e2.getMessage() + "]");
            }
        }
        return result;
    }

}
